import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import  {getMenu} from  '@/api/index'
import { useRouter } from 'vue-router'
import {routesData} from '@/hooks/routeTrick'
//侧边导航的收缩功能
export const useMenusStore = defineStore('menus', () => {
  const router  = useRouter()//获取路由对象
    const menuList =  ref(localStorage.getItem('menuList')?JSON.parse(localStorage.getItem('menuList')):[])
    const  getMenuList   = async ()=>{
        await getMenu().then(res=>{
        console.log(res,'===菜单')
       
         menuList.value =res.data.menus
         localStorage.setItem("menuList",JSON.stringify(menuList.value))
        }).catch(error=>{
        console.log("加载数据失败。。。",error);
    })
      }  
  
   //动态路路由添加
    async function  setRoutes(){
       //发送请求获取菜单数据
       await getMenuList()
        if(menuList.value&&menuList.value.length){
          let menus = routesData(menuList.value)
        console.log( '拼接之后的menus',menus)
        menus?.forEach(item=>router.addRoute('home',item))
        }      
    }


    return {menuList,getMenuList,setRoutes}
})
